package cn.agiledata.bank.myspace.action;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.uns.upms.util.excel.DocumentCompose;
import com.uns.upms.util.excel.DocumentComposeFactoryBean;
import cn.agiledata.bank.common.servlet.InitForString;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.myspace.bean.PrintTransactionHisBean;
import cn.agiledata.bank.myspace.bean.PrintTransactionHisQueryBean;
import cn.agiledata.bank.myspace.service.PrintTransactionHisService;
import com.vnv.infrastructure.action.IPBBaseAction;
import com.vnv.infrastructure.action.IPBBaseDynaForm;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class PrintTransactionHisAction extends IPBBaseAction implements
        Constant {
    /**
     * 查询企业对帐数据
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws IPBException
     * @throws Exception
     */
    public ActionForward toQueryPage(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws IPBException, Exception {

        IPBBaseDynaForm dynaForm = (IPBBaseDynaForm) form;

        String year = request.getParameter("selectYear");

        String month = request.getParameter("selectMonth");

        String accountId = String.valueOf(WeatherUtil
                .getAccountIdFromSession(request));

        if ((!StringUtil.isStrEmpty(year)) && (!StringUtil.isStrEmpty(month))) {
            String endMonth = "";
            String beginDate = year + "-" + month + "-" + "01";

            if (Integer.parseInt(month) < 9) {
                endMonth = "0" + (Integer.parseInt(month) + 1) + "";
            } else {
                endMonth = (Integer.parseInt(month) + 1) + "";
            }

            String endDate = year + "-" + endMonth + "-" + "01";

            dynaForm.getMap().put("beginDate", beginDate);
            dynaForm.getMap().put("endDate", endDate);
            request.setAttribute("beginDate", beginDate);
            request.setAttribute("endDate", endDate);
            request.setAttribute("year", year);
            request.setAttribute("month", month);
            if (accountId != null) {
                dynaForm.getMap().put("accountSeq", accountId);
            }
            PrintTransactionHisService printTransHis = (PrintTransactionHisService) IPBAppFactory
                    .getObj("printTransactionHisService");

            List list = printTransHis.getTransactionHisBydatePageTotal(dynaForm
                    .getMap());

            request.setAttribute("list", list);
            request.setAttribute("pageSize", new Integer(list.size()));
            
        }

        return mapping.findForward("transHisPage");
    }

    /**
     * 打印企业对帐单
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws IPBException
     * @throws Exception
     */
    public ActionForward PrintTransactionHisPage(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws IPBException, Exception {
        IPBBaseDynaForm dynaForm = (IPBBaseDynaForm) form;

        String accountId = String.valueOf(WeatherUtil
                .getAccountIdFromSession(request));
        String subAccountID = request.getParameter("subAccountID");

        dynaForm.get("beginDate").toString();
        dynaForm.get("endDate").toString();
        dynaForm.getMap().put("accountSeq", accountId);
        dynaForm.getMap().put("subAccountID", subAccountID);

        String startPage = request.getParameter("startPage");
        int start = Integer.parseInt(startPage);

        if (startPage.equals("1")) {
            dynaForm.getMap().put("startIndex", new Integer(1));
            dynaForm.getMap().put("endIndex", new Integer(PRINTPAGESIZE));
        } else {
            int startIndex = (start - 1) * PRINTPAGESIZE + 1;
            int endIndex = (start - 1) * PRINTPAGESIZE + PRINTPAGESIZE;
            dynaForm.getMap().put("startIndex", new Integer(startIndex));
            dynaForm.getMap().put("endIndex", new Integer(endIndex));

        }

        PrintTransactionHisService printTransHis = (PrintTransactionHisService) IPBAppFactory
                .getObj("printTransactionHisService");
        List list = printTransHis.getTransactionHisByDatePageList(dynaForm
                .getMap());

        PrintTransactionHisBean printBean = printTransHis
                .getLastMonthBalance(dynaForm.getMap());
        request.setAttribute("printBean", printBean);

        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        String str = df.format(date);

        request.setAttribute("date", str);
        request.setAttribute("list", list);

        String begin = dynaForm.get("beginDate").toString();
        String month = begin.substring(5, 7);
        String year = begin.substring(0, 4);
        request.setAttribute("year", year);
        request.setAttribute("month", month);

        String pageSize = request.getParameter("pageSize");
        String page = request.getParameter("page");
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("page", page);

        return mapping.findForward("printTransHisPage");
    }
    /**
     * 导出企业对帐单
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws IPBException
     * @throws Exception
     */
    public ActionForward exportTransHis(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws IPBException, Exception {
    	IPBBaseDynaForm dynaForm = (IPBBaseDynaForm) form;
    	Map mapExcel = new HashMap();
    	List listOut = new ArrayList();
    	//首先判断是否有记录. 瓶装查询记录条数 subaccountid的 查询方法的条件
    	String year = request.getParameter("selectYear");
        String month = request.getParameter("selectMonth");
        String accountId = String.valueOf(WeatherUtil
                .getAccountIdFromSession(request));
        if ((!StringUtil.isStrEmpty(year)) && (!StringUtil.isStrEmpty(month))) {
            String endMonth = "";
            String beginDate = year + "-" + month + "-" + "01";
            if (Integer.parseInt(month) < 9) {
                endMonth = "0" + (Integer.parseInt(month) + 1) + "";
            } else {
                endMonth = (Integer.parseInt(month) + 1) + "";
            }
            String endDate = year + "-" + endMonth + "-" + "01";
            dynaForm.getMap().put("beginDate", beginDate);
            dynaForm.getMap().put("endDate", endDate);
            if (accountId != null) {
                dynaForm.getMap().put("accountSeq", accountId);
            }
        }
        PrintTransactionHisService printTransHis = (PrintTransactionHisService) IPBAppFactory
        .getObj("printTransactionHisService");
        List totalList = printTransHis.getTransactionHisBydatePageTotal(dynaForm
        		.getMap());
        //没有交易记录是导出空的带有无记录提示信息的excel.
        if (totalList == null || totalList.size() <= 0) {
        	Map queryTitleMap = new HashMap();
            queryTitleMap.put("DATETITLE", "当前时间段内没有查找到任何交易记录.");
            mapExcel.put(DocumentComposeFactoryBean.VALUE_NORMAL, queryTitleMap);
    		OutputStream os = response.getOutputStream();
    		response.setContentType("application/vnd.ms-excel");
    		//调用已经定义好的模板.
    		DocumentCompose compose = DocumentComposeFactoryBean.xlsComposeFactory(
    				"exporttranshis", os, mapExcel);
    		//导出文件到本地
    		os = compose.composeXlsStream();
    		os.flush();
    		os.close();
    		response.flushBuffer();
            return null;
        }
        //有交易记录. 根据上面所得的记录条数 查出所有交易 导出到excel
        int i = totalList.size();
        PrintTransactionHisQueryBean temp = (PrintTransactionHisQueryBean) totalList.get(0);  
        dynaForm.getMap().put("subAccountID", String.valueOf(temp.getSubAccountId()));
        int endIndex = (i - 1) * PRINTPAGESIZE + PRINTPAGESIZE;
        dynaForm.getMap().put("startIndex", new Integer(1));
        dynaForm.getMap().put("endIndex", new Integer(endIndex));
        List list = printTransHis.getTransactionHisByDatePageList(dynaForm
                .getMap());

        PrintTransactionHisBean printBean = printTransHis
                .getLastMonthBalance(dynaForm.getMap());

        String begin = dynaForm.get("beginDate").toString();
        String months = begin.substring(5, 7);
        String years = begin.substring(0, 4);
        //
        Map queryTitleMap = new HashMap();
        queryTitleMap.put("DATETITLE", "交易时间:");
        queryTitleMap.put("DATE", years + "年" + months + "月");
        queryTitleMap.put("NAMETITLE", "账户名:");
        queryTitleMap.put("NAME", printBean.getName());
        queryTitleMap.put("SUBNAMETITLE", "子账户:");
        queryTitleMap.put("SUBNAME", printBean.getSubAccountName());
        queryTitleMap.put("BALANCETITLE", "上月余额:");
        if (printBean.getBalance() > 0) {
        	queryTitleMap.put("BALANCE", new Double(printBean.getBalance()));
        }
        mapExcel.put(DocumentComposeFactoryBean.VALUE_NORMAL, queryTitleMap);
        Map title = new HashMap();
		title.put("BEGINDATE", "日期");
		title.put("TRANSID", "交易编号");
		title.put("ACTIONTYPE", "交易类型");
		title.put("PURPOSE", "资金用途");
		title.put("GATHERING", "收款额");
		title.put("PAYMENT", "付款额");
		title.put("BALANCE", "余额");
		title.put("EMAIL", "对方账号");
		listOut.add(title);
        if (list != null && list.size() > 0) {
        	List listId =InitForString.getListId("ACTION_TYPE");
    		List listName=InitForString.getListName("ACTION_TYPE");
        	for (int j = 0; j < list.size(); j++) {
        		Map exchange = new HashMap();
        		PrintTransactionHisBean printTrans = (PrintTransactionHisBean) list.get(j);
        		exchange.put("BEGINDATE", printTrans.getBeginDate());
        		exchange.put("TRANSID", printTrans.getTransId());
        		if (printTrans.getActionSeq() != 0) {
	        		for (int jj = 0; jj < listId.size(); jj++) {
	        			if ( listId.get(jj).equals(new Long(printTrans.getActionSeq()))){
	        				exchange.put("ACTIONTYPE", listName.get(jj));
	        			}
	        		}
        		}
        		exchange.put("PURPOSE", printTrans.getPurpose());
        		exchange.put("GATHERING", printTrans.getGathering());
        		exchange.put("PAYMENT", printTrans.getPayment());
        		exchange.put("BALANCE", new Double(printTrans.getBalance()));
        		exchange.put("EMAIL", printTrans.getEmail());
        		listOut.add(exchange);
        	}
        }
        mapExcel.put(DocumentComposeFactoryBean.VALUE_LINE, listOut);
		
		OutputStream os = response.getOutputStream();
		response.setContentType("application/vnd.ms-excel");
		//调用已经定义好的模板.
		response.setHeader("Content-disposition", "attachment; filename="+URLEncoder.encode("对账单"+".xls","UTF-8"));//设置表头
		DocumentCompose compose = DocumentComposeFactoryBean.xlsComposeFactory(
				"exporttranshis", os, mapExcel);
		//导出文件到本地
		os = compose.composeXlsStream();
		os.flush();
		os.close();
		response.flushBuffer();
        return null;
    }

}
